import './index.scss'
import { App } from 'antd'
import { useMount } from 'ahooks'
import { useRequest } from 'alova'
import { lazy, Suspense, useState } from 'react'

import { useNavigate } from 'react-router-dom'

import { Http } from '../Api'
import { debuggerFun } from '../Utils/Judgment'
import { IndexedDBResetting, SetKey, AddIndexdDB } from '../Utils/IndexedDB'

const LoadSvg = lazy(() => import('../Views/LoadSvg'))
const { hostname } = window.location

const Log = () => {
    const Navigate = useNavigate()
    const { notification } = App.useApp()
    const [Data, setData] = useState()
    const [Template, setTemplate] = useState()
    const { send } = useRequest(params => Http({ url: 'getProjectConfigInfo', params }), { immediate: false })
    const getRouter = async (data) => {
        const { key, config } = data
        const [{
            apiUrl,
            authUrl,
            client_Id,
            client_Secret,
            grant_Type,
            fullName,
            imageUrl,
            login,
            loginMethod,
            isDebug,
            isScan,
        }] = config
        const configDB = {
            API: apiUrl,
            AUTH: authUrl,
            client_id: client_Id,
            client_secret: client_Secret,
            grant_type: grant_Type,
            fullName,
            imageUrl,
            login,
            loginMethod,
            isDebug,
            isScan
        }
        window.API = apiUrl
        window.AUTH = authUrl
        await SetKey('key', key)
        await AddIndexdDB('config', configDB)
        if (isDebug) debuggerFun()
        setData(configDB)
        setTemplate(lazy(() => import(`./LoginBox/${login || client_Id}.jsx`)))
    }
    useMount(() => {
        IndexedDBResetting()
        sessionStorage.clear()
        send({ WebUrl: hostname })
            .then(res => getRouter(res))
            .catch(async () => {
                // 临时数据
                const config = {
                    API: 'https://jszxtest-rest.ljkjkf.com/api',
                    AUTH: 'https://jszxtest-rest.ljkjkf.com/auth',
                    client_id: 'jszxtest',
                    fullName: '测试版',
                    imageUrl: 'https://image.ljkjkf.com/intellisiteSystem_TieKe/WebTemplate/Common/'
                }

                await SetKey('key', '77031bd5-d101-42ee-9307-4a2146b22a14')
                await AddIndexdDB('config', config)

                notification.error({
                    key: 'sign',
                    message: `项目信息初始化失败!`,
                    description: '请检测网络状态或联系管理员.',
                    onClose: () => Navigate('Start')
                })
            })
    })

    return (
        <div className='LoginPage'>
            <Suspense fallback={<LoadSvg />}>
                {Data && Template ? <Template config={Data} /> : <LoadSvg />}
            </Suspense>
        </div>
    );

};

export default Log;